import { ajax, Promise } from 'drunk-base';
import { getToken, removeToken } from './Auth';
import { TOKEN_KEY } from './Config';

export function postForm(url: string, formElement: HTMLFormElement, headers?: any) {
    return ajax({
        url,
        method: "POST",
        headers,
        data: new FormData(formElement),
        responseType: 'json',
    });
}

export function getJson(url: string, data?: Object, headers?: any) {
    return ajax({
        url,
        data,
        headers,
        responseType: 'json',
    });
}

export function postJson(url: string, data?: Object, headers?: any) {
    return ajax({
        url,
        data,
        method: "POST",
        headers,
        contentType: 'application/json',
        responseType: 'json',
    })
}

export function putJson(url: string, data?: Object, headers?: any) {
    return ajax({
        url,
        data,
        method: 'PUT',
        headers,
        responseType: 'json',
        contentType: 'application/json',
    });
}

export function deleteJson(url: string, headers?: any) {
    return ajax({
        url,
        method: "DELETE",
        headers,
        responseType: 'json',
    });
}

export function getJsonWithToken(url: string, data?: Object) {
    return getJson(url, data, {
        [TOKEN_KEY]: getToken()
    }).catch(onException);
}

export function postJsonWithToken(url: string, data?: Object) {
    return postJson(url, data, {
        [TOKEN_KEY]: getToken()
    }).catch(onException);
}

export function putJsonWithToken(url: string, data?: Object) {
    return putJson(url, data, {
        [TOKEN_KEY]: getToken()
    }).catch(onException);
}

export function deleteJsonWithToken(url: string) {
    return deleteJson(url, {
        [TOKEN_KEY]: getToken()
    }).catch(onException);
}

function onException(res): Promise<any> {
    if (res.xhr.status === 401) {
        removeToken();
        location.href = '#/login';

        return Promise.reject({
            res: { message: "登录态已失效，请重新登录" },
            xhr: res.xhr
        });
    }
    return Promise.reject(res);
}